var fs = require('fs');
var url = require('url');
var open = require('open');
var highlight = require('cli-highlight').highlight;

var fisConfig = 'deploy-hosts.json';

function formatReceiverUrl(hostName, port) {
	var u = url.parse(hostName);
	u.host = ''; // 清除一下 host ,https://cnodejs.org/topic/5865f13c189fd5ad64590096
	u.port = port;
	u.pathname = '/receiver.php';
	return url.format(u);
}

module.exports = {
	openBrowser: function (url) {
		open(url);
	},
	parserConfig: function (data) {
		var result = {};
		for (var mediaName in data) {
			var itemList = data[mediaName];
			var index = 0;
			for (var i = 0; i < itemList.length; i++) {
				var item = itemList[i];

				var infoList = item.portAndRoots;
				infoList.sort(function(a, b){
					return parseInt(a.id, 10) - parseInt(b.id, 10);
				}).forEach(function (info) {
					result[mediaName + (index > 0 ? index : '')] = {
						receiver: formatReceiverUrl(item.host, info.port),
						root: info.root,
						// visitPort: info.visitPort,
						webUrl: info.visitPort ? item.host + ':' + info.visitPort : ''
					}
					index++;
				});
			}
		}
		return JSON.stringify(result, null, '\t');
	},
	writeFisConfig: function (str) {
		fs.open(fisConfig, 'w+', function opened(err, fd) {
			if (err) {
				throw err;
			}
			fs.write(fd, str, function (err, written) {
				if (err) {
					throw err;
				}
			});
		})
	},
	readFisConfig: function () {
		console.log('读取 fis 配置:', fisConfig);
		if (fs.existsSync(fisConfig)) {
			return JSON.parse(fs.readFileSync(fisConfig, {
				encoding: 'utf8'
			}));
		} else {
			throw Error('当前目录下并没有发现 fis 配置:', fisConfig);
		}
	},
	validateMedia: function (media) {
		if (!media) {
			throw Error('请指定一个 RD 配置的名称！');
		}
	},
	getMediaConfig: function (media) {
		this.validateMedia(media);
		var mediaConfig = (this.readFisConfig())[media];
		if (mediaConfig) {
			return mediaConfig;
		} else {
			throw Error('您的配置中并没有该 RD 的主机信息：', media);
		}

	},
	getRdHostVisitURL: function (media) {
		var mediaConfig = this.getMediaConfig(media);
		if (mediaConfig.visitPort) {
			return this.parseVisitUrl(mediaConfig.receiver, mediaConfig.visitPort);
		} else {
			throw Error('缺少 RD 主机的访问端口');
		}
	},
	parseVisitUrl: function (receiver, visitPort) {
		var parsed = url.parse(receiver);
		// console.log( parsed)
		parsed.port = visitPort;
		parsed.pathname = '';
		parsed.host = '';
		return url.format(parsed);
	},
	// 查看一个指定的 media 的配置
	view: function (media) {
		var mediaConfig = this.getMediaConfig(media);
		console.log('查看配置：', media);
		this.colorPrint(mediaConfig);
	},
	// 查看一个指定的 media 的配置（模糊匹配）
	scan: function (mediaStr) {
		this.validateMedia(mediaStr);
		var conf = this.readFisConfig();
		var ret = {};
		for (var media in conf) {
			if (media.indexOf(mediaStr) > -1) {
				ret[media] = conf[media];
			}
		}
		if (Object.keys(ret).length) {
			console.log('查看配置：', mediaStr);
			this.colorPrint(ret);
		} else {
			console.log('未匹配到相关配置。');
		}
	},
	// 高亮输出数据
	colorPrint: function ( data ) {
		console.log(highlight((data), {language: 'json', ignoreIllegals: true}));
	},
}